'use client'

import { useTheme } from 'next-themes'
import { useEffect, useState } from 'react'

export default function DarkModeToggle() {
    // 用于处理服务器端渲染和客户端渲染不匹配的问题
    const [mounted, setMounted] = useState(false)
    // 使用 resolvedTheme 而不是 theme，因为它会给出实际应用的主题
    const { resolvedTheme, setTheme } = useTheme()

    // 组件挂载后再显示，避免水合不匹配
    useEffect(() => {
        setMounted(true)
    }, [])

    // 在客户端渲染完成前不显示任何内容
    if (!mounted) {
        return null
    }

    // 切换主题的处理函数
    const toggleTheme = () => {
        setTheme(resolvedTheme === 'dark' ? 'light' : 'dark')
    }

    return (
        <button
            onClick={toggleTheme}
            className="relative p-2 rounded-lg "
            aria-label={resolvedTheme === 'dark' ? '切换到亮色模式' : '切换到暗色模式'}
        >
            {/* 太阳图标 - 暗色模式下显示 */}
            <svg
                className={`w-5 h-5 transition-all duration-300 hover:scale-110 hover:rotate-12 ${resolvedTheme === 'dark' ? 'scale-0 absolute' : 'scale-100 text-gray-800'
                    }`}
                fill="none"
                stroke="currentColor"
                viewBox="0 0 24 24"
            >
                <path
                    strokeLinecap="round"
                    strokeLinejoin="round"
                    strokeWidth={2}
                    d="M12 3v1m0 16v1m9-9h-1M4 12H3m15.364 6.364l-.707-.707M6.343 6.343l-.707-.707m12.728 0l-.707.707M6.343 17.657l-.707.707M16 12a4 4 0 11-8 0 4 4 0 018 0z"
                />
            </svg>

            {/* 月亮图标 - 亮色模式下显示 */}
            <svg
                className={`w-5 h-5 transition-all duration-300 hover:scale-110 hover:rotate-12 ${resolvedTheme === 'dark' ? 'scale-100 text-yellow-300' : 'scale-0 absolute'
                    }`}
                fill="none"
                stroke="currentColor"
                viewBox="0 0 24 24"
            >
                <path
                    strokeLinecap="round"
                    strokeLinejoin="round"
                    strokeWidth={2}
                    d="M20.354 15.354A9 9 0 018.646 3.646 9.003 9.003 0 0012 21a9.003 9.003 0 008.354-5.646z"
                />
            </svg>
        </button>
    )
}